package vaccination;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import utils.DBController;
import utils.*;

public class Login extends HttpServlet {
    private static Logger log = Logger.getLogger(Login.class); //avvio logger di log4j
    @Override
    public void init() {
        PropertyConfigurator.configure(Login.class.getClassLoader().getResource("utils/log4j.properties"));
    }
    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        DBController dbController = DBController.getInstance();
        
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        //prende i parametri
        String user = request.getParameter("username");
        String password = request.getParameter("password");
        String typeUser = request.getParameter("type");
        String error_message = "";
        User currentUser = null;
        
        try 
        {
            if(user != null && password != null){
                // richiama la funzione per verificare la corrispondenza dei dati inseriti con un utente (medico o paziente)
                currentUser = dbController.loginUser(request, out, user, password, typeUser);
                
                if(currentUser == null) {
                    error_message = "Username o Password non corretti";
                } else if(currentUser.isRegistered()==0){
                            if(typeUser.equals("doctors")) {
                                response.sendRedirect("dottore_registration.html");
                            }
                            
                            if(typeUser.equals("patients")) {
                                response.sendRedirect("paziente_registration.html");
                            }
                            
                    
                        } else {
                            
                            //crea la nuova sessione
                            HttpSession session = request.getSession();
                            session.setAttribute("user", currentUser);

                            // richiede il cookie del precedente login e lo salva nel cookie dell'ultimo accesso dell'utente indicato
                            Cookie cookies[] = request.getCookies();
                            for(int i=0; i<cookies.length; i++)
                                if(cookies[i].getName().equals("Vaccination-currentlogin-"+currentUser.getUsername())){
                                    //ultimo accesso nell'anno
                                    Cookie lastLoginCookie = new Cookie("Vaccination-lastlogin-"+currentUser.getUsername(), cookies[i].getValue());
                                    lastLoginCookie.setMaxAge(2592000); //ultimo anno
                                    response.addCookie(lastLoginCookie);
                                }

                            // salva quindi il nuovo cookie con l'orario corrente di accesso
                            Calendar cal = Calendar.getInstance();
                            Date date = cal.getTime();                            
                            Cookie currentLoginCookie = new Cookie("Vaccination-currentlogin-"+currentUser.getUsername(), Utils.formatDateTime(date));
                            currentLoginCookie.setMaxAge(2592000); //ultimo anno
                            response.addCookie(currentLoginCookie);

                            response.sendRedirect("Home");
                        }
            }
            
            //NEL CASO DI ERRORE
            String message = error_message+"" +
                    "<br>" +
                    "<br>" +
                    "<a href=\"login.html\">\n" +
                    "<button class=\"btn btn-primary btn-danger\">Back</button> \n" +
                    "</a>";
            Utils.printHeader(request, out, "Errore!");
            Utils.printError(request, out, message);
            Utils.printFooter(out);
            
        } catch(Exception e){
            //stampa tramite log4j il messaggio dell'eccezione
            log.error(e.getMessage());
            String message = e.getMessage()+"" +
                    "<br>" +
                    "<br>" + 
                    "<a href=\"login.html\">\n" +
                    "<button class=\"btn btn-primary btn-danger\">Back</button> \n" +
                    "</a>";
            
            Utils.printHeader(request, out, "Errore!");
            Utils.printError(request, out, message);
            Utils.printFooter(out);
        } finally {            
            out.close();
        }
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
